/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param p int整型 
     * @param q int整型 
     * @return int整型
     */
    // JZ86一样的代码
    /*
    int lowestCommonAncestor(TreeNode* root, int p, int q) {
        if(!root) return -1; 
        if(root->val == p || root->val == q) return root->val;
        int left = lowestCommonAncestor(root->left, p, q);
        int right = lowestCommonAncestor(root->right, p ,q);
        if(left == -1 && right != -1) return right;
        if(left != -1 && right == -1) return left;
        if(left!=-1 && right!=-1) return root->val;
        return -1;
    }
    */
    // 考虑二叉树的性质
    int lowestCommonAncestor(TreeNode* root, int p, int q) {
        TreeNode* tmp = root;
        while(1) {
            if(tmp->val < p && tmp->val < q)
                tmp = tmp -> right;
            else if(tmp->val > p && tmp -> val > q)
                tmp = tmp -> left;
            else break;
        }
        return tmp->val;
    }
};